package com.yinhang;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import com.learn.utils.DateUtils;

public class ToWebHtml {
	
	final static String transUrl = "http://css.webank.org.cn";

	/**
	 * 正则需要转义字符：'$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|'
	 */
	@Test
	public void test() throws Exception {
		long start = System.currentTimeMillis();
		File dir = new File("D:\\PHPnow-1.5.6\\vhosts\\yh.com\\templets\\cngold");
		if(dir.exists() && dir.isDirectory()){
			File[] files = dir.listFiles();
            for(File file : files){
            	if(file.getName().indexOf(".htm")>0){
            		System.out.println(file);
            		writeHtmlToFile(file);
            	}
            }
		}
		long end = System.currentTimeMillis();
		System.out.println("times="+(end-start)+"ms");
	}

	public void writeHtmlToFile(File file) {
		System.out.println(file.getName());
		try {
			String origin = FileUtils.readFileToString(file, Charset.forName("GBK"));
			origin = origin.replaceAll("\\{dede:global\\.cfg_cmspath/\\}/templets", transUrl);
			origin = origin.replaceAll("\\[field:global\\.cfg_cmspath/\\]/templets", transUrl);
			FileUtils.writeStringToFile(new File("target/yinhang/" + getFilename(file.getName())), origin, Charset.forName("GBK"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFilename(String name) {
		if (StringUtils.isNotBlank(name)) {
			return name;
		} else {
			String FileExtensions = "";
			String[] arry = name.split("\\.");
			if (arry.length > 0) {
				FileExtensions = arry[arry.length - 1];
			}
			Random rd = new Random();
			return DateUtils.getTimestamp() + rd.nextInt(1000) + "." + FileExtensions;
		}
	}
}
